<template>
  <div class="customer-list">
    <div class="header">
      <h2>客户资料</h2>
      <div class="header-actions">
        <el-button @click="showReviewDrawer">审核记录</el-button>
        <el-button type="primary" @click="handleAdd">新增客户</el-button>
      </div>
    </div>

    <div class="filter">
      <el-form :model="filterForm" inline>
        <el-form-item label="关键词">
          <el-input v-model="filterForm.keyword" placeholder="客户名称/法人/电话" clearable />
        </el-form-item>
        <el-form-item label="合作状态">
          <el-select
            v-model="filterForm.is_cooperation"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="未合作" :value="0" />
            <el-option label="已合作" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading="loading">
      <el-table-column prop="name" label="客户名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="legal_person" label="法定代表人" width="120" show-overflow-tooltip />
      <el-table-column prop="phone" label="联系电话" width="120" show-overflow-tooltip />
      <el-table-column prop="industry" label="行业" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.industry_name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="scale" label="企业规模" width="120" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.scale_name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="user_name" label="负责人" width="100" show-overflow-tooltip />
      <el-table-column prop="is_cooperation" label="合作状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.is_cooperation ? 'success' : 'info'">
            {{ row.is_cooperation ? '已合作' : '未合作' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="customer_status_name"
        label="会员状态"
        width="100"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-tag :type="getMemberStatusTagType(row.customer_status)">
            {{ row.customer_status_name || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="140" show-overflow-tooltip />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleDetail(row)">查看</el-button>
          <el-dropdown size="small">
            <el-button type="default" size="small">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                <el-dropdown-item @click="handleFollowup(row)">跟进</el-dropdown-item>
                <el-dropdown-item @click="handleAddTrace(row)">
                  <el-icon><ChatDotRound /></el-icon>
                  销售机会
                </el-dropdown-item>
                <el-dropdown-item divided></el-dropdown-item>
                <el-dropdown-item @click="handleOrder(row, 1)">非诉讼订单</el-dropdown-item>
                <el-dropdown-item @click="handleOrder(row, 2)">诉讼订单</el-dropdown-item>
                <el-dropdown-item divided @click="handleDelete(row)" style="color: #f56c6c">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 客户详情对话框（使用新组件） -->
    <CustomerDetailNew
      v-model="detailVisible"
      :customer-id="currentCustomerId"
      @edit="handleEditFromDetail"
      @add-contact="handleAddContact"
      @edit-contact="handleEditContact"
      @add-followup="handleAddFollowup"
      @add-order="handleAddOrder"
    />

    <!-- 新增/编辑客户对话框（使用新组件） -->
    <CustomerFormNew
      v-model="formVisible"
      :customer-id="currentCustomerId"
      @success="handleFormSuccess"
    />

    <!-- 跟进记录对话框 -->
    <FollowupForm
      v-model="followupVisible"
      :customer-id="currentCustomerId"
      :customer-name="currentCustomerName"
      @success="handleFollowupSuccess"
    />

    <!-- 非诉讼订单对话框 -->
    <NonLawsuitOrderForm
      v-model="nonLawsuitOrderVisible"
      :order-id="currentOrderId"
      :customer-id="currentCustomerId"
      @success="handleOrderSuccess"
    />

    <!-- 诉讼订单对话框 -->
    <LawsuitOrderForm
      v-model="lawsuitOrderVisible"
      :order-id="currentOrderId"
      :customer-id="currentCustomerId"
      @success="handleOrderSuccess"
    />

    <!-- 审核记录抽屉 -->
    <CustomerReviewDrawer v-model="reviewDrawerVisible" @success="getCustomerList" />

    <!-- 销售机会抽屉 -->
    <OpportunityForm
      v-model="opportunityFormVisible"
      :customer-id="currentCustomerId"
      :customer-name="currentCustomerName"
      :opportunity-id="0"
      :mode="'create'"
      @success="handleOpportunitySuccess"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown, ChatDotRound } from '@element-plus/icons-vue'
  import CustomerDetailNew from './components/CustomerDetailNew.vue'
  import CustomerFormNew from './components/CustomerFormNew.vue'
  import FollowupForm from './components/FollowupForm.vue'
  import LawsuitOrderForm from './components/LawsuitOrderForm.vue'
  import NonLawsuitOrderForm from './components/NonLawsuitOrderForm.vue'
  import CustomerReviewDrawer from './components/CustomerReviewDrawer.vue'
  import OpportunityForm from './components/OpportunityForm.vue'
  import { customerApi } from '@/api/crm'
  import { lawsuitLegalOrderApi } from '@/api/crm/lawsuitLegalOrderApi'
  import type { Customer, Option } from '@/types/crm'

  const loading = ref(false)
  const tableData = ref<Customer[]>([])
  const detailVisible = ref(false)
  const formVisible = ref(false)
  const followupVisible = ref(false)
  const lawsuitOrderVisible = ref(false)
  const nonLawsuitOrderVisible = ref(false)
  const reviewDrawerVisible = ref(false)
  const orderVisible = ref(false)
  const specialFormVisible = ref(false)
  const opportunityFormVisible = ref(false)
  const currentOrderId = ref(0)
  const currentCustomerId = ref(0)
  const currentCustomerName = ref('')

  const filterForm = reactive({
    keyword: '',
    is_cooperation: '',
  })

  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0,
  })

  const industryOptions = ref<Option[]>([])
  const scaleOptions = ref<Option[]>([])

  // 获取客户列表
  const getCustomerList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.current,
        limit: pagination.size,
        keyword: filterForm.keyword,
        is_cooperation: filterForm.is_cooperation ? Number(filterForm.is_cooperation) : undefined,
      }
      const res = await customerApi.list(params)
      tableData.value = res.data.list
      pagination.total = res.data.total
    } catch (error) {
      console.error('获取客户列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      // 获取行业选项
      const industryRes = await customerApi.industryOptions()
      industryOptions.value = industryRes.data || []

      // 获取规模选项
      const scaleRes = await customerApi.scaleOptions()
      scaleOptions.value = scaleRes.data || []
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 获取行业标签
  const getIndustryLabel = (value: number) => {
    const option = industryOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取规模标签
  const getScaleLabel = (value: number) => {
    const option = scaleOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取会员状态标签类型
  const getMemberStatusTagType = (status?: number): string => {
    if (!status) return 'info'
    // 根据会员状态值返回不同的标签类型
    return status === 2 ? 'success' : 'warning'
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getCustomerList()
  }

  // 重置
  const handleReset = () => {
    filterForm.keyword = ''
    filterForm.is_cooperation = ''
    pagination.current = 1
    getCustomerList()
  }

  // 分页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    getCustomerList()
  }

  // 当前页改变
  const handleCurrentChange = (current: number) => {
    pagination.current = current
    getCustomerList()
  }

  // 新增客户
  const handleAdd = () => {
    currentCustomerId.value = 0
    formVisible.value = true
  }

  // 编辑客户
  const handleEdit = (row: any) => {
    currentCustomerId.value = row.id
    formVisible.value = true
  }

  // 查看详情
  const handleDetail = (row: any) => {
    currentCustomerId.value = row.id
    detailVisible.value = true
  }

  // 从详情页点击编辑
  const handleEditFromDetail = (customerId: number) => {
    detailVisible.value = false // 关闭详情抽屉
    currentCustomerId.value = customerId
    formVisible.value = true // 打开编辑抽屉
  }

  // 客户跟进
  const handleFollowup = (row: any) => {
    currentCustomerId.value = row.id
    currentCustomerName.value = row.name
    followupVisible.value = true
  }

  // 业务提单
  const handleOrder = (row: any, category: number) => {
    currentCustomerId.value = row.id
    currentOrderId.value = 0

    if (category === 1) {
      // 非诉讼订单
      nonLawsuitOrderVisible.value = true
    } else if (category === 2) {
      // 诉讼订单
      lawsuitOrderVisible.value = true
    }
  }

  // 删除客户
  const handleDelete = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除该客户吗？', '提示', {
        type: 'warning',
      })

      await customerApi.delete(row.id)
      ElMessage.success('删除成功')
      getCustomerList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除客户失败:', error)
      }
    }
  }

  // 表单提交成功
  const handleFormSuccess = () => {
    formVisible.value = false
    getCustomerList()
  }

  // 跟进提交成功
  const handleFollowupSuccess = () => {
    followupVisible.value = false
    ElMessage.success('跟进记录添加成功')
  }

  // 普通订单提交成功
  const handleOrderSuccess = () => {
    orderVisible.value = false
    ElMessage.success('普通订单创建成功')
  }

  // 特殊订单提交成功
  const handleSpecialOrderSuccess = () => {
    specialFormVisible.value = false
    ElMessage.success('特殊订单创建成功')
  }

  // 打开销售机会抽屉
  const handleAddTrace = (row: Customer) => {
    currentCustomerId.value = Number(row.id) || 0
    currentCustomerName.value = row.name
    opportunityFormVisible.value = true
  }

  // 销售机会提交成功
  const handleOpportunitySuccess = () => {
    opportunityFormVisible.value = false
    ElMessage.success('销售机会添加成功')
  }

  // 显示审核记录抽屉
  const showReviewDrawer = () => {
    reviewDrawerVisible.value = true
  }

  // 从详情页点击新增联系人
  const handleAddContact = (customerId: number) => {
    currentCustomerId.value = customerId
    // TODO: 打开新增联系人对话框
    console.log('新增联系人', customerId)
    ElMessage.info('新增联系人功能开发中')
  }

  // 从详情页点击编辑联系人
  const handleEditContact = (contactId: number) => {
    // TODO: 打开编辑联系人对话框，传递contactId
    console.log('编辑联系人', contactId)
    ElMessage.info('编辑联系人功能开发中')
  }

  // 从详情页点击新增跟进
  const handleAddFollowup = (customerId: number) => {
    currentCustomerId.value = customerId
    followupVisible.value = true
  }

  // 从详情页点击新增订单
  const handleAddOrder = (customerId: number) => {
    currentCustomerId.value = customerId
    // 默认打开普通订单
    orderVisible.value = true
  }

  onMounted(() => {
    getCustomerList()
    getOptions()
  })
</script>

<style scoped>
  .customer-list {
    padding: 20px;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }

  .filter {
    background: #f5f7fa;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }
</style>
